package com.knife.news.logic.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.knife.news.logic.NewsService;
import com.knife.news.logic.RelativeService;
import com.knife.news.object.News;
import com.knife.news.object.Relative;

public class RelativeServiceImpl extends DAOSupportService implements RelativeService {
	
	private NewsService newsDAO = new NewsServiceImpl();
	private static RelativeServiceImpl typedao = new RelativeServiceImpl();

	public static RelativeServiceImpl getInstance() {
		return typedao;
	}

	public boolean saveRelative(Relative rel) {
		com.knife.news.model.Relative brel=new com.knife.news.model.Relative();
		brel.setRelative(rel);
		return this.dao.save(brel);
	}

	public boolean updateRelative(Relative rel) {
		com.knife.news.model.Relative brel=new com.knife.news.model.Relative();
		brel.setRelative(rel);
		return this.dao.update(brel);
	}

	public boolean delRelative(Relative rel) {
		com.knife.news.model.Relative brel=new com.knife.news.model.Relative();
		brel.setRelative(rel);
		return this.dao.del(brel);
	}
	
	public Relative getRelativeById(String id){
		com.knife.news.model.Relative brel = (com.knife.news.model.Relative) this.dao.get(com.knife.news.model.Relative.class, id);
		return new Relative(brel);
	}
	
	public Relative getRelativeByNewsId(String newsid){
		Collection<Object> paras = new ArrayList<Object>();
		paras.add(newsid);
		List<Relative> rels= changeListType(this.dao.query(com.knife.news.model.Relative.class, "k_news_id=?",paras));
		if(rels.size()>0){
			return rels.get(0);
		}else{
			return null;
		}
	}
	
	public List<News> getRelatedNewsById(String newsid){
		List<News> aNews=new ArrayList<News>();
		Relative aRel=this.getRelativeByNewsId(newsid);
		if(aRel!=null){
			if(aRel.getRels()!=null){
				String[] ids=aRel.getRels().split(",");
				for(String id : ids){
					News aNew=newsDAO.getNewsById(id);
					if(aNew!=null){
						aNews.add(aNew);
					}
				}
			}
		}
		return aNews;
	}
	
	public List<Relative> changeListType(List<Object> objs){
		List<Relative> results = new ArrayList<Relative>();
		if(objs!=null){
			for (Object newobj : objs) {
				com.knife.news.model.Relative robj = (com.knife.news.model.Relative) newobj;
				Relative tobj =  new Relative(robj);
				results.add(tobj);
			}
		}
		return results;	
	}
}